/*
 Copyright 2008 Todd Ditchendorf. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are permitted 
 provided that the following conditions are met:
 
 1. Redistributions of source code must retain the above copyright notice, this list of conditions 
 and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright notice, this list of 
 conditions and the following disclaimer in the documentation and/or other materials provided 
 with the distribution.
 
 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TODD DITCHENDORF OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 POSSIBILITY OF SUCH DAMAGE.
 */

//
//  MediaKeysPlugin.m
//  MediaKeysPlugin
//
//  Created by Aaron Zinman on 7/25/09.
//
//  MediaKeysPlugin is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  MediaKeysPlugin is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with MediaKeysPlugin.  If not, see <http://www.gnu.org/licenses/>.

#import "MediaKeysPlugIn.h"
#import "TODBrowserPlugInController.h"

static MediaKeysPlugIn *sharedSingletonDelegate = nil;

@interface MediaKeysPlugIn ()
@property (readwrite, retain) id <TODBrowserPlugInController> plugInController;

@property (readwrite, copy) NSString *identifier;
@property (readwrite, copy) NSString *localizedTitle;
@property (readwrite) NSInteger allowedViewPlacementMask;
@property (readwrite) NSInteger preferredViewPlacementMask;
@property (readwrite, copy) NSString *preferredMenuItemKeyEquivalent;
@property (readwrite) NSUInteger preferredMenuItemKeyEquivalentModifierMask;
@property (readwrite, copy) NSString *toolbarIconImageName;
@property (readwrite, copy) NSString *preferencesIconImageName;
@property (readwrite, retain) NSDictionary *defaultsDictionary;
@property (readwrite, retain) NSDictionary *aboutInfoDictionary;
@property CGFloat preferredVerticalSplitPosition;
@property CGFloat preferredHorizontalSplitPosition;
@end

@implementation MediaKeysPlugIn

+ (MediaKeysPlugIn *)sharedInstance {
  // Can be nil unless initialized
  return sharedSingletonDelegate;
}

- (void) sendForward {
  NSString *js = @"if (mediaKeysPlugin && mediaKeysPlugin.forward) {"
                  "  mediaKeysPlugin.forward();"
                  "}";
  WebView *wv = [plugInController mainWebView];
  [wv stringByEvaluatingJavaScriptFromString:js];
}

- (void) sendBackward {
  NSString *js = @"if (mediaKeysPlugin && mediaKeysPlugin.backward) {"
                  "  mediaKeysPlugin.backward();"
                  "}";
  WebView *wv = [plugInController mainWebView];
  [wv stringByEvaluatingJavaScriptFromString:js];
}

- (void) sendPlay {
  NSString *js = @"if (mediaKeysPlugin && mediaKeysPlugin.play) {"
                  "  mediaKeysPlugin.play();"
                  "}";
  WebView *wv = [plugInController mainWebView];
  [wv stringByEvaluatingJavaScriptFromString:js];
}

- (NSViewController *)makePlugInViewController {
  return nil;
}

- (NSViewController *)preferencesViewController {
  return nil;
}

- (id)initWithBrowserPlugInController:(id <TODBrowserPlugInController>)controller {
	self = [super init];
	if (self != nil) {
    assert(sharedSingletonDelegate == nil);
    sharedSingletonDelegate = self;
		self.plugInController = controller;
		self.identifier = @"com.azinman.MediaKeysPlugIn";
		self.localizedTitle = @"MediaKeys";
		self.preferredMenuItemKeyEquivalent = @"";//@"c";
		self.preferredMenuItemKeyEquivalentModifierMask = 0; //(NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask);
		self.toolbarIconImageName = @"";//@"clipboard";
		self.preferencesIconImageName = @"";//@"clipboardx32_32";
		self.allowedViewPlacementMask = 0;
//                    (TODBrowserPlugInViewPlacementDrawerMask|
//										 TODBrowserPlugInViewPlacementUtilityPanelMask|
//										 TODBrowserPlugInViewPlacementFloatingUtilityPanelMask|
//										 TODBrowserPlugInViewPlacementHUDPanelMask|
//										 TODBrowserPlugInViewPlacementFloatingHUDPanelMask|
//										 TODBrowserPlugInViewPlacementSplitViewLeftMask|
//										 TODBrowserPlugInViewPlacementSplitViewRightMask|
//										 TODBrowserPlugInViewPlacementSplitViewBottomMask);

		self.preferredViewPlacementMask = 0;//TODBrowserPlugInViewPlacementDrawerMask;
    
    NSLog(@"Hijacking NSApplication's sendEvent");
    NSError *error = nil;
    [NSApplication jr_swizzleMethod:@selector(sendEvent:) withMethod:@selector(interceptedSendEvent:) error:&error];
    if (error != nil) {
      NSLog(@"Oh noes, error while swizzling! domain: %@, code %d, userInfo: %@", [error domain], [error code], [error userInfo]);
    } else {
      NSLog(@"Hijack successful.. YEY!");
    }
  }
	return self;
}


- (void)dealloc {	
  NSLog(@"deallocing mediakeys, undoing hijack");
  NSError *error = nil;
  [NSApplication jr_swizzleMethod:@selector(sendEvent:) withMethod:@selector(interceptedSendEvent:) error:&error];
  if (error != nil) {
    NSLog(@"Oh noes, error while swizzling! domain: %@, code %d, userInfo: %@", [error domain], [error code], [error userInfo]);
  } else {
    NSLog(@"De-Hijack successful.. YEY!");
  }

  sharedSingletonDelegate = nil;
	self.plugInController = nil;
	self.identifier = nil;
	self.localizedTitle = nil;
	self.preferredMenuItemKeyEquivalent = nil;
	self.toolbarIconImageName = nil;
	self.preferencesIconImageName = nil;
	self.defaultsDictionary = nil;
	self.aboutInfoDictionary = nil;
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

#pragma mark TODBrowserPlugInNotifications

- (void)plugInViewControllerDidAppear:(NSNotification *)notification {
}


- (void)plugInViewControllerDidDisappear:(NSNotification *)notification {
}


- (void)setAboutInfoDictionary:(NSDictionary *)info {
	[aboutInfoDictionary release];
	aboutInfoDictionary = [info retain];
}

- (NSDictionary *)aboutInfoDictionary {
	if (!aboutInfoDictionary) {
		NSString *credits = [[[NSAttributedString alloc] initWithString:@"" attributes:nil] autorelease];
		NSString *applicationName = @"Fluid MediaKeys Plug-in";
		NSImage  *applicationIcon = nil; //[NSImage imageNamed:self.preferencesIconImageName];
		NSString *version = @"1.0";
		NSString *copyright = @"Aaron Zinman 2009";
		NSString *applicationVersion = @"1.0";
		
		self.aboutInfoDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
									credits, @"Credits",
									applicationName, @"ApplicationName",
									applicationIcon, @"ApplicationIcon",
									version, @"Version",
									copyright, @"Copyright",
									applicationVersion, @"ApplicationVersion",
									nil];
	}
	return aboutInfoDictionary;
}

@synthesize plugInController;
@synthesize identifier;
@synthesize localizedTitle;
@synthesize allowedViewPlacementMask;
@synthesize preferredViewPlacementMask;
@synthesize preferredMenuItemKeyEquivalent;
@synthesize preferredMenuItemKeyEquivalentModifierMask;
@synthesize toolbarIconImageName;
@synthesize preferencesIconImageName;
@synthesize defaultsDictionary;
@synthesize preferredVerticalSplitPosition;
@synthesize preferredHorizontalSplitPosition;
@end
